<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>项目部署</title>
    <style type="text/css">
        body {
            background: #F2F3F5;
        }

        .ver-layout {
            display: flex;
            flex-direction: column;
        }

        .hor-layout {
            display: flex;
            flex-direction: row;
        }

        #codeView {
            font-weight: bold;
            padding: 10px;
            background: white;
            border-radius: 10px;
        }
    </style>
</head>
<body>
<div class="container">
    <button id="deploy_button" type="button">测试请求</button>
    <code class="code-layout">
        <pre id="codeView">
        </pre>
    </code>
</div>
<!-- js代码 -->
<script>

//请求数据
function request(url, method, params, body) {
  return new Promise((resolve, reject) => {
    let paramsStr = params && Object.entries(params).map(([key, value]) => `${key}=${value}`).join("&")
    paramsStr = paramsStr ? `?${paramsStr}` : ""
    let bodyStr = body ? JSON.stringify(body) : ""
    let xhr = new XMLHttpRequest();
    xhr.open(method, url + paramsStr)
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send(bodyStr);
    xhr.onload = function () {
      let {code, data, msg} = JSON.parse(xhr.responseText)
      if (code == 0) return resolve(data)
      else return reject(msg)
    }
    xhr.onerror = function () {
      return reject("网络异常！")
    }
  })
}

//请求测试功能
function requestTest() {
  let deploy_button = document.getElementById("deploy_button")
  let codeView = document.getElementById("codeView")
  deploy_button.addEventListener("click", async () => {
    let {error, stdout, stderr} = await request("/deployProject", "get")
    codeView.innerText = stdout
  })
}

//sse测试
function sseTest() {
  let codeView = document.getElementById("codeView")
  const eventSource = new EventSource('/sse/events');
  //消息监听
  eventSource.onmessage = function (event) {
    console.log("EventSource===onmessage传入消息", event.data)
    if (event.data === 'end') {
      eventSource.close()
    } else {
      let color = event.data && event.data.indexOf("####") == -1 ? "black" : "#00CD7F"
      let codeLine = `<p style="color:${color}">${event.data}</p>`
      codeView.innerHTML = codeView.innerHTML + codeLine
    }
  };
  //连接成功
  eventSource.onopen = function (event) {
    console.log('EventSource===onopen连接打开')
  }
  //连接出错
  eventSource.onerror = function (error) {
    if (eventSource.readyState === EventSource.CLOSED) {
      // 连接已关闭，可能需要重新连接
      console.error('EventSource===onerror连接断掉了:', error);
    }
  }
}

function main() {
  requestTest()
  sseTest()
}

main()
</script>
</body>
</html>
